<template>
	<view class="bullectChat-wrap">
		<view v-for="(listItem, i) in list" :key="listItem.key" class="bullectChat" :style="[style]">
			<view v-for="(n,i) in listItem.list" :key="n.id" class="bullectChat-item"
				:style="{'--duration': n.duration + 'ms'}">
				<slot name="item" :data="n"></slot>
			</view>
		</view>
	</view>
</template>
<script>
	import TaskQueue from "../../taskQueue.js"
	export default {
		props: {
			//滚动时长
			duration: {
				type: [Number, Array],
				default: 5000,
			},
			column: {
				type: Number,
				default: 1
			},
			itemW: {
				type: Number,
				default: 200
			},
			gap: {
				type: Number,
				default: 50
			},
			loop: {
				type: Boolean,
				default: false
			},
			style: {
				type: Object,
				default: () => {}
			}
		},
		data() {
			return {
				list: [],
				current: -1,
				taskQueue: null
			}
		},
		created() {
			if (this.column > 1) {
				let column = this.column
				while (column > 0) {
					this.list.push({
						key: column,
						list: []
					})
					column--
				}
				this.current = -1
			} else {
				this.list = [{
					key: 1,
					list: []
				}]
			}
			this.taskQueue = new TaskQueue({
				start: (info) => {
					this.list[info.index].list.push(info)
				},
				end: (info) => {
					setTimeout(async () => {
						await this.sleep(info.duration)
						this.list[info.index].list.shift()
						if(this.loop){
							this.add(info)
						}
					})
				}
			})
		},
		beforeUnmount(){
			this.taskQueue?.destroy()
			this.taskQueue = null
		},
		methods: {
			sleep(delay) {
				return new Promise(res => {
					let timer = setTimeout(() => {
						res()
					}, delay)
				})
			},
			getCurrent() {
				if (this.column <= 1) return 0
				if (this.current >= this.column - 1) {
					this.current = 0
				} else {
					this.current++
				}
				return this.current
			},
			getRandomInt(min, max) {
				const _min = Math.ceil(min);
				const _max = Math.floor(max);
				return Math.floor(Math.random() * (_max - _min + 1)) + min;
			},
			add(bullectChats) {
				const list = Array.isArray(bullectChats) ? bullectChats : [bullectChats]
				let delay = 0
				list.forEach((e) => {
					let _duration = this.duration
					if (Array.isArray(_duration)) {
						_duration = this.getRandomInt(_duration[0], _duration[1])
					}
					delay = (this.itemW / this.column) / (this.itemW + 750) * _duration

					this.taskQueue.add({
						...e,
						duration: _duration - delay,
						index: this.getCurrent()
					}, delay)
				})

				this.delay_now = Date.now()
			},
			
			pause(){
				this.taskQueue.pause()
			},
			play(){
				this.taskQueue.play()
			}
		}
	}
</script>
<style lang="scss" scoped>
	.bullectChat {
		position: relative;
		width: 100vw;
	}

	.bullectChat-item {
		position: absolute;
		top: 0;
		right: 0;
		transform: translateX(100%);
		animation: move var(--duration) linear forwards;
	}

	@keyframes move {
		to {
			transform: translateX(-750rpx);
		}
	}
</style>